/**
 * 
 */
package agg;

import java.io.UnsupportedEncodingException;

/**
 * Tools to aid in converting from and to different Hex representations.
 * @author Hardeep
 */
public class HexTools {
	static final byte[] HEX_CHAR_TABLE = {
		(byte)'0', (byte)'1', (byte)'2', (byte)'3',
		(byte)'4', (byte)'5', (byte)'6', (byte)'7',
		(byte)'8', (byte)'9', (byte)'a', (byte)'b',
		(byte)'c', (byte)'d', (byte)'e', (byte)'f'
	};
	
	/**
	 * Given an array of bytes, create and return a HEX representation as a 
	 * String.
	 * @param digest
	 * @return
	 */
	public static String byteArrayToHexString(byte[] digest) {
		StringBuilder hex = new StringBuilder("");
		int decValue;
		String hexVal = "";
		for (int i=0; i<digest.length; i++) {
			if (digest[i] >= 0)
				decValue = digest[i];
			else
				decValue = 256 + digest[i];

			hexVal = Integer.toHexString(decValue);
			if (hexVal.length() == 1) hexVal = "0" + hexVal;
			hex.append(hexVal);
		}
		return hex.toString();
	}

	/**
	 * Given an array of bytes, convert them to a String representation using
	 * hex characters.
	 * @param raw
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String toHexString(byte[] raw) 
	throws UnsupportedEncodingException 
	{
		byte[] hex = new byte[2 * raw.length];
		int index = 0;

		for (byte b : raw) {
			int v = b & 0xFF;
			hex[index++] = HEX_CHAR_TABLE[v >>> 4];
			hex[index++] = HEX_CHAR_TABLE[v & 0xF];
		}
		return new String(hex);
	}
	
	
	public static String bufferToHex(byte buffer[]) {
		return HexTools.bufferToHex(buffer, 0, buffer.length);
	}
	
	public static String bufferToHex(byte buffer[], int startOffset, int length)
	{
		StringBuffer	hexString = new StringBuffer(2 * length);
		int				endOffset = startOffset + length;

		for (int i = startOffset; i < endOffset; i++)
		{
			HexTools.appendHexPair(buffer[i], hexString);
		}

		return hexString.toString();
	}

	private static void appendHexPair(byte b, StringBuffer hexString)
	{
		char	highNibble = kHexChars[(b & 0xF0) >> 4];
		char	lowNibble = kHexChars[b & 0x0F];

		hexString.append(highNibble);
		hexString.append(lowNibble);
	}

	private static final char kHexChars[] = {
		'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };
}
